<template>
  <div class="home-bg">
    <div class="home-header">
      工作台
      <van-icon name="scan" class="scan-icon" @click="onScan" />
    </div>
    <van-search v-model="value" placeholder="搜索流程" class="home-search" />
    <div class="home-stats">
      <div class="stat-card orange" @click="goDaiban('todo')">
        <div class="stat-icon"><van-icon name="notes-o" /></div>
        <div class="stat-title">待我处理</div>
        <div class="stat-num">{{ todoCount }}</div>
      </div>
      <div class="stat-card blue" @click="goDaiban('mine')">
        <div class="stat-icon"><van-icon name="user-o" /></div>
        <div class="stat-title">我发起的</div>
        <div class="stat-num">{{ mineCount }}</div>
      </div>
      <div class="stat-card purple" @click="goDaiban('cc')">
        <div class="stat-icon"><van-icon name="friends-o" /></div>
        <div class="stat-title">抄送我的</div>
        <div class="stat-num">{{ ccCount }}</div>
      </div>
    </div>
    <van-collapse v-model="activeGroups" class="home-group-list">
      <van-collapse-item
        v-for="group in groups"
        :key="group.name"
        :title="group.name + '（' + group.items.length + '）'"
        :name="group.name"
        toggle="true"
      >
        <div class="group-items">
          <div
            class="group-item"
            v-for="item in group.items"
            :key="item.title"
            @click="goFlowDetail(item)"
          >
            <div class="item-icon"><van-icon name="cluster-o" /></div>
            <div class="item-title" :title="item.title">{{ item.title }}</div>
          </div>
        </div>
      </van-collapse-item>
    </van-collapse>
  </div>
</template>
<script>
import { getGroupList, getHomeStaticData } from "@/api/api.js";

export default {
  name: "home",
  data() {
    return {
      value: "",
      activeGroups: [],
      groups: [], // 初始为空，接口获取
      todoCount: 0,
      mineCount: 0,
      ccCount: 0,
    };
  },
  created() {
    this.fetchGroups();
    this.fetchHomeStaticData();
  },
  methods: {
    async fetchGroups() {
      try {
        const res = await getGroupList();
        if (res.data && (res.data.status === 0 || res.data.success)) {
          const raw = res.data.data || [];
          this.groups = raw
            .map((item) => ({
              name: item.name,
              items: (item.groups || []).map((flow) => ({
                id: flow.id,
                title: flow.name,
                imgUrl: flow.imgUrl,
              })),
            }))
            .filter((g) => g.items.length > 0);
        } else {
          this.$toast("获取分组失败");
        }
      } catch (e) {
        this.$toast("获取分组异常");
      }
    },
    async fetchHomeStaticData() {
      const res = await getHomeStaticData();
      console.log("res:", res);
      if (res.data && (res.data.status === 0 || res.data.success)) {
        this.todoCount = res.data.data.todoNum;
        this.mineCount = res.data.data.initiatedNum;
        this.ccCount = res.data.data.ccNum;
      }
    },
    goFlowDetail(item) {
      // 跳转到流程详情页，携带id
      this.$router.push({
        path: "/flowCreate",
        query: { id: item.id },
      });
    },
    onScan() {
      // 检查浏览器是否支持调用相机
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        this.$toast("您的浏览器不支持访问相机");
        return;
      }

      // 请求相机权限
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
          // 相机权限获取成功，可以在这里添加扫码逻辑
          this.$toast("相机已开启");
          // 记得在使用完后关闭相机流
          stream.getTracks().forEach((track) => track.stop());
        })
        .catch((error) => {
          this.$toast("无法访问相机：" + error);
        });
    },
    goDaiban(type) {
      this.$router.push({ path: "/daiban", query: { type } });
    },
  },
};
</script>
<style scoped>
.home-bg {
  /* min-height: 100vh; */
  background: #f6f8fa;
  padding-bottom: 0;
}
.home-header {
  background: #1677ff;
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  padding: 18px 0 12px 0;
  letter-spacing: 2px;
  position: relative;
}
.scan-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 24px;
  color: #fff;
}
.home-search {
  margin: 16px 12px 12px 12px;
  border-radius: 24px;
  background: #fff;
}
.home-stats {
  display: flex;
  justify-content: space-between;
  margin: 0 12px 18px 12px;
  gap: 10px;
}
.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #1677ff11;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0 8px 0;
}
.stat-card .stat-icon {
  font-size: 28px;
  margin-bottom: 4px;
}
.stat-card.orange .stat-icon {
  color: #ff9800;
}
.stat-card.blue .stat-icon {
  color: #1677ff;
}
.stat-card.purple .stat-icon {
  color: #8e24aa;
}
.stat-title {
  font-size: 13px;
  color: #666;
}
.stat-num {
  font-size: 18px;
  font-weight: bold;
  color: #222;
}
.home-group-list {
  margin: 0 0 20px 0;
}
.group-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 8px;
}
.group-item {
  width: 70px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.item-icon {
  background: #e3f2fd;
  border-radius: 12px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  margin-bottom: 4px;
}
.item-title {
  font-size: 13px;
  color: #333;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
